package com.yc.sole.erp.biz;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.yc.sole.erp.dto.CategoryAttributeDto;
import com.yc.sole.erp.dto.CategoryDto;
import com.yc.sole.erp.exception.ErpResultEnum;
import com.yc.sole.erp.repository.CategoryAttributeRepository;
import com.yc.sole.erp.repository.CategoryRepository;
import com.yc.sole.erp.request.CategoryAttributeQueryReq;
import com.yc.sole.erp.request.CategoryAttributeReq;
import com.yc.sole.erp.response.CategoryAttributeResp;
import com.yc.sole.common.enums.OptionType;
import com.yc.sole.framework.exception.BaseException;
import com.yc.sole.framework.mybatis.page.Paging;
import com.yc.sole.framework.mybatis.util.PageUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 服务接口实现
 *
 * @author yizuomin
 * @date 2024-01-13
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class CategoryAttributeBiz {

    private final CategoryAttributeRepository categoryAttributeRepository;
    private final CategoryRepository categoryRepository;

    /**
     * 新增
     *
     * @param categoryAttributeReq
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveCategoryAttribute(CategoryAttributeReq categoryAttributeReq) {
        // 参数验证
        this.validate(categoryAttributeReq);
        CategoryDto categoryDto = categoryRepository.selectCategoryById(categoryAttributeReq.getCategoryId());
        if (Objects.isNull(categoryDto)) {
            throw new BaseException(ErpResultEnum.CATEGORY_NOT_FOUND);
        }
        CategoryAttributeDto dto = new CategoryAttributeDto();
        BeanUtil.copyProperties(categoryAttributeReq, dto);
        categoryAttributeRepository.saveCategoryAttribute(dto);
    }

    /**
     * 修改
     *
     * @param categoryAttributeReq
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateCategoryAttributeById(CategoryAttributeReq categoryAttributeReq) {
        // 参数验证
        this.validate(categoryAttributeReq);
        CategoryAttributeDto dto = new CategoryAttributeDto();
        BeanUtil.copyProperties(categoryAttributeReq, dto);
        if (OptionType.INPUT.equals(dto.getOptionType())) {
            dto.setManuallyAdded(null);
            dto.setOptional(null);
        }
        categoryAttributeRepository.updateCategoryAttributeById(dto);
    }

    /**
     * 参数验证
     *
     * @param categoryAttributeReq
     */
    private void validate(CategoryAttributeReq categoryAttributeReq) {
        if (!OptionType.INPUT.equals(categoryAttributeReq.getOptionType())) {
            if (CharSequenceUtil.isBlank(categoryAttributeReq.getOptional())) {
                throw new BaseException(ErpResultEnum.CATEGORY_OPTION_CAN_NOT_EMPTY);
            }
            if (Objects.isNull(categoryAttributeReq.getManuallyAdded())) {
                throw new BaseException(ErpResultEnum.MANUALLY_ADDED_CAN_NOT_EMPTY);
            }
            Pattern pattern = Pattern.compile("^[^|]+(?:\\|[^|]+)*$");
            Matcher matcher = pattern.matcher(categoryAttributeReq.getOptional());
            if (!matcher.find()) {
                throw new BaseException("每两个选项之间请以|分隔");
            }
        }
    }

    /**
     * 删除
     *
     * @param ids
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteCategoryAttributeByIds(Collection<Long> ids) {
        categoryAttributeRepository.deleteCategoryAttributeByIds(ids);
    }

    /**
     * 根据产品分类查询
     *
     * @param categoryId
     * @return
     */
    public List<CategoryAttributeResp> selectByCategoryId(Long categoryId) {
        return BeanUtil.copyToList(categoryAttributeRepository.selectByCategoryId(categoryId), CategoryAttributeResp.class);
    }

    /**
     * 分页查询
     *
     * @param page
     * @param categoryAttributeQueryReq
     * @return
     */
    public Paging<CategoryAttributeResp> selectCategoryAttributePage(Paging<CategoryAttributeQueryReq> page, CategoryAttributeQueryReq categoryAttributeQueryReq) {
        Paging<CategoryAttributeDto> paging = categoryAttributeRepository.selectCategoryAttributePage(page, categoryAttributeQueryReq);
        Paging<CategoryAttributeResp> categoryAttributeRespPaging = PageUtil.pageCopy(paging, CategoryAttributeResp.class);
        if (CollUtil.isEmpty(categoryAttributeRespPaging.getRecords())) {
            return categoryAttributeRespPaging;
        }
        Set<Long> categoryIds = categoryAttributeRespPaging.getRecords().stream().map(CategoryAttributeResp::getCategoryId).collect(Collectors.toSet());
        Map<Long, CategoryDto> categoryDtoMap = categoryRepository.selectCategoryByIds(categoryIds).stream().collect(Collectors.toMap(CategoryDto::getId, v -> v));
        for (CategoryAttributeResp categoryAttributeResp : categoryAttributeRespPaging.getRecords()) {
            CategoryDto categoryDto = categoryDtoMap.get(categoryAttributeResp.getCategoryId());
            if (Objects.nonNull(categoryDto)) {
                categoryAttributeResp.setCategoryName(categoryDto.getCategoryName());
            }
        }
        return categoryAttributeRespPaging;
    }

    /**
     * 通过id查询分类属性
     *
     * @param categoryAttrId
     * @return
     */
    public CategoryAttributeResp selectCategoryAttributeById(Long categoryAttrId) {
        return BeanUtil.copyProperties(categoryAttributeRepository.selectCategoryAttributeById(categoryAttrId), CategoryAttributeResp.class);
    }
}
